package com.unknownman.block.service.impl;

import static org.cloud.constant.UserDataDimensionConstant.USER_DIMENSION_CACHE_KEY;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.lianziyou.chain.common.api.CommonPage;
import com.lianziyou.chain.common.api.CommonResult;
import com.unknownman.block.constants.ChainContractConstants;
import com.unknownman.block.entity.TContractConfig;
import com.unknownman.block.mapper.TContractConfigMapper;
import com.unknownman.block.service.TContractConfigService;
import com.unknownman.block.transaction.InitChainTranSubscribe;
import java.util.Set;
import javax.annotation.PostConstruct;
import org.cloud.constant.CoreConstant;
import org.cloud.core.redis.RedisUtil;
import org.cloud.entity.LoginUserDetails;
import org.cloud.exception.BusinessException;
import org.cloud.utils.CommonUtil;
import org.cloud.utils.DataDimensionUtil;
import org.cloud.utils.RedissonUtil;
import org.cloud.utils.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * NFT合约配置 服务实现类
 * </p>
 *
 * @author xhy
 * @since 2021-10-18
 */
@Service
public class TContractConfigServiceImpl extends ServiceImpl<TContractConfigMapper, TContractConfig> implements TContractConfigService {

    @Lazy
    @Autowired
    private InitChainTranSubscribe initChainTranSubscribe;

    @Autowired
    RedisUtil redisUtil;

    @Value("${system.DataDimension.open:false}")
    private Boolean isSystemDataDimensionOpen;

    @Override
    public CommonPage<TContractConfig> findListByPage(Integer page, Integer limit, String orderBy,
        QueryWrapper<TContractConfig> queryWrapper) {

        if (isSystemDataDimensionOpen) {
            Set<String> contractAddressDataDimension = DataDimensionUtil.single().getCurrentUserDataDimensionByName("contract_address");
            if (!contractAddressDataDimension.contains("***")) {
                queryWrapper.in("contract_address", contractAddressDataDimension);
            }
        }

        if (StringUtils.isEmpty(orderBy)) {
            PageHelper.startPage(page, limit);
        } else {
            PageHelper.startPage(page, limit, orderBy);
        }
        List<TContractConfig> list = baseMapper.selectList(queryWrapper);
        return CommonPage.restPage(list);
    }

    @Override
    public List<TContractConfig> getListByStatus(ChainContractConstants.ContractStatusConstants contractStatus) {
        QueryWrapper<TContractConfig> queryWrapper = new QueryWrapper<>();
        if (contractStatus != null) {
            queryWrapper.eq("contract_status", contractStatus.getStatus());
        }
        return list(queryWrapper);
    }

    @Override
    public List<TContractConfig> getListByChainConfigId(Long chiaConfigId, ChainContractConstants.ContractStatusConstants contractStatus) {
        QueryWrapper<TContractConfig> queryWrapper = new QueryWrapper<>();
        if (chiaConfigId != null) {
            queryWrapper.eq("chain_config_id", chiaConfigId);
        }
        if (contractStatus != null) {
            queryWrapper.eq("contract_status", contractStatus.getStatus());
        }
        return list(queryWrapper);
    }

    @Override
    public CommonResult updateContract(TContractConfig config) throws BusinessException {
        TContractConfig contractConfig = baseMapper.selectById(config.getContractConfigId());
        if (ObjectUtils.isEmpty(contractConfig)) {
            throw new BusinessException("合约配置不存在");
        }
        config.setUpdateBy(CommonUtil.single().getLoginUser().getUsername());
        int insert = baseMapper.updateById(config);
        if (insert == 0) {
            throw new BusinessException("修改失败");
        }
        initChainTranSubscribe.clearSubscribe(contractConfig.getChainConfigId());
        return CommonResult.success();
    }

    @Override
    public CommonResult addContract(TContractConfig config) throws BusinessException {
        LoginUserDetails loginUser = CommonUtil.single().getLoginUser();
        config.setCreateBy(loginUser.getUsername());
        config.setUpdateBy(loginUser.getUsername());
        int insert = baseMapper.insert(config);
        if (insert == 0) {
            throw new BusinessException("修改失败");
        }
        initChainTranSubscribe.clearSubscribe(config.getChainConfigId());
        return CommonResult.success();
    }

    @Override
    public CommonResult updateStatus(Long contractConfigId, Integer status) throws BusinessException {
        TContractConfig chainConfig = baseMapper.selectById(contractConfigId);
        if (ObjectUtils.isEmpty(chainConfig)) {
            throw new BusinessException("链配置不存在");
        }
        TContractConfig config = new TContractConfig();
        config.setContractConfigId(contractConfigId);
        config.setContractStatus(status);
        int update = baseMapper.updateById(config);
        if (update == 0) {
            throw new BusinessException("更新失败");
        }
        initChainTranSubscribe.clearSubscribe(chainConfig.getChainConfigId());
        return CommonResult.success();
    }

    @Override
    public TContractConfig getBySymbol(String symbol) {
        QueryWrapper<TContractConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TContractConfig::getSymbol, symbol);
        return getBaseMapper().selectOne(queryWrapper);
    }
}
